package com.bdqn.business.academic.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bdqn.business.academic.dao.ChapterMapper;
import com.bdqn.business.academic.dao.SelectionMapper;
import com.bdqn.entity.academic.Chapter;
import com.bdqn.entity.academic.Selection;
import com.bdqn.response.PageResult;
import com.bdqn.response.Result;
import com.bdqn.response.ResultCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachePut;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Map;

@Service
@Transactional
public class SelectionService {


    @Autowired
    private SelectionMapper selectionMapper;

    @Autowired
    private ChapterMapper chapterMapper;

    public Result getList(Map<String, Object> map) {

        QueryWrapper<Selection> selectionQueryWrapper = new QueryWrapper<>();

        selectionQueryWrapper.orderByDesc("create_time");

        Integer page = Integer.parseInt(map.get("page").toString());
        Integer size = Integer.parseInt(map.get("size").toString());

        IPage<Selection> selectionIPage = new Page<>(page,size);

        IPage<Selection> selectionResult = selectionMapper.selectPage(selectionIPage, selectionQueryWrapper);

        PageResult<Selection> selectionPageResult = new PageResult<>(selectionResult.getTotal(),selectionResult.getRecords());

        return new Result(ResultCode.SUCCESS,selectionPageResult);
    }

    @CachePut(cacheNames = "selection",key = "#selection.id")
    public Result saveSelection(Selection selection) {
        Chapter chapter = chapterMapper.selectById(selection.getChapterId());
        selection.setChapterName(chapter.getName());
        selection.setStatus("1"); //启用
        selection.setCreateTime(new Date());


        if(selection.getSelectionContent().contains("<img")){
            selection.setSelectionContent(selection.getSelectionContent().replaceAll("<img","<img width='300px' height='300px' "));
        }

        selectionMapper.insert(selection);
        return new Result(ResultCode.SUCCESS,selection);
    }
}
